package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 陈辉
 * @data 2023 9:13
 */
@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Autowired
    private CacheService cacheService;
    /**
     * 查询所有频道
     *
     * @return
     */
    @Override
    public ResponseResult findAll() {
        //优化思路： 使用redis缓存频道列表数据
        //先查缓存
        String channelsJSON = cacheService.get("channels");
        //缓存有：直接返回
        if (!StringUtils.isEmpty(channelsJSON)){
            List channels = JSON.parseObject(channelsJSON, List.class);
            return ResponseResult.okResult(channels);
        }else{
            //缓存没有：查询数据库，并添加到缓存
            List<WmChannel> channels = list();
            cacheService.set("channels",JSON.toJSONString(channels));
            return ResponseResult.okResult(channels);
        }


    }
}
